package com.atguigu.juc.future;

import java.util.concurrent.*;

/**
 * @Description:  runAsync supplyAsync 测试
 * @author： yeswater
 * @create： 2024/5/28
 */

public class CompletableFutureBuildDemo {
	public static void main(String[] args) throws ExecutionException, InterruptedException {
		//m1();
		//m2();
		m3();
		m4();
	}
	
	/**
	 * runAsync(Runnable runnable) 测试
	 * ForkJoinPool.commonPool-worker-9
	 * null
	 */
	private static void m1() throws InterruptedException, ExecutionException {
		CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
			System.out.println(Thread.currentThread().getName());
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
		});
		System.out.println(completableFuture.get());
	}
	
	/**
	 * runAsync(Runnable runnable,Executor executor) 测试
	 * pool-1-thread-1
	 * null
	 */
	private static void m2() throws InterruptedException, ExecutionException {
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		
		CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
			System.out.println(Thread.currentThread().getName());
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
		}, threadPool);
		System.out.println(completableFuture.get());
		
		threadPool.shutdown();
	}
	
	/**
	 * supplyAsync(Supplier<U> supplier) 测试
	 * ForkJoinPool.commonPool-worker-9
	 * hello supplyAsync
	 */
	private static void m3() throws InterruptedException, ExecutionException {
		CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
			System.out.println(Thread.currentThread().getName());
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			return "hello supplyAsync";
		});
		System.out.println(completableFuture.get());
	}
	
	/**
	 * supplyAsync(Supplier<U> supplier,Executor executor) 测试
	 * pool-1-thread-1
	 * hello supplyAsync
	 */
	private static void m4() throws InterruptedException, ExecutionException {
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		
		CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
			System.out.println(Thread.currentThread().getName());
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			return "hello supplyAsync";
		}, threadPool);
		System.out.println(completableFuture.get());
		
		threadPool.shutdown();
	}
}
